<template>
	<d2-container>
		<template slot="header">
			<el-form class="header-area" ref="indexForm" :model="indexForm" label-width="100px" style="height: auto">
				<el-row>
					<el-col :span="4" v-if="shopId == 0">
						<el-form-item label="选择门店" prop="shopId">
							<el-select v-model="indexForm.shopId" placeholder="请选择" style="width: 100%;">
								<el-option value="0" label="请选择">请选择</el-option>
								<el-option value="10" label="科德店">科德店</el-option>
								<el-option value="11" label="江南万达店">江南万达店</el-option>
								<el-option value="12" label="秀灵店">秀灵店</el-option>
							</el-select>
						</el-form-item>
					</el-col>

                    <el-col :span="4">
					    <el-form-item label="商品类型" prop="categoryType">
						  <el-select v-model="indexForm.categoryType" style="width: 100%;">
							<el-option label="主食" value="1"></el-option>
							<el-option label="加菜" value="2"></el-option>
							<el-option label="自选/饮料" value="3"></el-option>
						  </el-select>
					    </el-form-item>
				    </el-col>
					<el-col :span="4">
					    <el-form-item label="渠道类型" prop="channelType">
						  <el-select v-model="indexForm.channelType" style="width: 100%;">
							<el-option label="全部" value=""></el-option>
							<el-option label="门店订单" value="1"></el-option>
							<el-option label="美团核销" value="2"></el-option>
							<el-option label="抖音核销" value="3"></el-option>
						  </el-select>
					    </el-form-item>
				    </el-col>
					<el-col :span="8">
						<el-form-item label="时间范围" prop="time">
							<el-date-picker
								v-model="indexForm.time"
								type="datetimerange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="timestamp"
								:default-time="['00:00:00', '23:59:59']"
								@change="chooseDay"
								style="width: 100%"
							></el-date-picker>
						</el-form-item>
					</el-col>
					<el-col :span="4">
						<div class="search-submit">
							<el-button type="primary" size="medium" loading v-if="loading">查询</el-button>
							<el-button type="primary" size="medium" @click="submitForm('indexForm')" v-else>查询</el-button>

							<el-button type="primary" plain size="medium" @click="resetForm('indexForm')">重置</el-button>

              <el-button type="warning" size="medium" @click="exportForm('indexForm')">导出</el-button>
						</div>
					</el-col>
				</el-row>
			</el-form>
		</template>

		<template>
			<el-table :data="tableData" stripe border show-summary :summary-method="getSummaries" style="width: 100%">
				<el-table-column type="index" fixed label="排序" width="80"></el-table-column>
				<el-table-column prop="productId" label="商品ID" width="80"></el-table-column>
				<el-table-column prop="productName" label="商品名称"></el-table-column>
				<el-table-column prop="categoryName" label="商品分类名称" width="140"></el-table-column>
				<el-table-column prop="minPrice" label="最低售价" width="120" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="maxPrice" label="最高售价" width="120" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="payAmount" label="实收金额" width="120" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="orderAmount" label="应收金额（含赠送金额）" width="140" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="salesQuantity" label="销量（含赠送数量）" width="140"></el-table-column>
				<el-table-column prop="giftAmount" label="赠送金额" width="120" :formatter="moneyFilter"></el-table-column>
				<el-table-column prop="giftQuantity" label="赠送数量" width="120"></el-table-column>
			</el-table>
		</template>
	</d2-container>
</template>
<script>
import { findProductSaleVolumeList, exportProductSalesData } from '@api/restaurant/tempReport'
import dayjs from 'dayjs'
import { mapState } from 'vuex'
export default {
  name: 'tempReport-productSaleVolume',
  data () {
    return {
      indexForm: {
        shopId: '0',
        categoryType: '1',
        channelType: '',
        time: [dayjs().startOf('month'), dayjs().endOf('month')]
      },

      startTime: dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss'),
      endTime: dayjs().endOf('month').format('YYYY-MM-DD HH:mm:ss'),

      tableData: [],
	  loading: false
    }
  },
  computed: {
	  ...mapState('d2admin/permission', ['shopId'])
  },
  mounted () {
    this.indexForm.shopId = this.shopId == 0 ? '10' : this.shopId.toString()
    this.fetchData()
  },
  methods: {
    fetchData () {
      if (this.loading) {
        return
      }
      this.loading = true
      findProductSaleVolumeList({
        shopId: this.indexForm.shopId,
        categoryType: this.indexForm.categoryType,
        channelType: this.indexForm.channelType,
        startTime: this.startTime,
        endTime: this.endTime
      })
        .then(res => {
          this.tableData = res.data
          this.loading = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    getSummaries (param) { // 表格小计
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 5) {
          sums[index] = '小计'
          return
        }

        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          if (index == 8 || index == 10) {
            // 数量
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
          } else if (index == 6 || index == 7 || index == 9) {
            // 金额
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = Number(sums[index]).toFixed(2)
          }
        } else {
          sums[index] = ''
        }
      })

      return sums
    },
    moneyFilter (row, column, cellValue, index) {
      let value = cellValue
	  if (value == '' || value == null || value == undefined) {
        return '0.00'
	  } else if (value == 0) {
        return '0.00'
	  } else {
        let newVal = parseFloat(value)
        if (newVal < 0) {
          value = (-1 * parseFloat((value + '').replace(/[^\d\.-]/g, ''))).toFixed(2) + ''
        } else {
          value = parseFloat((value + '').replace(/[^\d\.-]/g, '')).toFixed(2) + ''
        }

        let left = value.split('.')[0].split('').reverse()
        let right = value.split('.')[1]

        let t = ''
        for (let i = 0; i < left.length; i++) {
          t += left[i] + ((i + 1) % 3 === 0 && (i + 1) !== left.length ? ',' : '')
        }

        if (newVal < 0) {
          return '-' + t.split('').reverse().join('') + '.' + right
        } else {
          return t.split('').reverse().join('') + '.' + right
        }
	  }
    },

    chooseDay (val) {
	  this.startTime = dayjs(val[0]).format('YYYY-MM-DD HH:mm:ss')
	  this.endTime = dayjs(val[1]).format('YYYY-MM-DD HH:mm:ss')
    },
    submitForm (formName) {
      this.fetchData()
    },
    resetForm () {
      // this.$refs[formName].resetFields()
      this.indexForm.shopId = this.shopId == 0 ? '10' : this.shopId.toString()
	  this.indexForm.categoryType = '1'
	  this.indexForm.channelType = ''
      this.indexForm.time = [dayjs().startOf('month'), dayjs().endOf('month')]
	  this.startTime = dayjs().startOf('month').format('YYYY-MM-DD HH:mm:ss')
	  this.endTime = dayjs().endOf('month').format('YYYY-MM-DD HH:mm:ss')

      this.fetchData()
    },
    exportForm () {
      exportProductSalesData({
        shopId: this.indexForm.shopId,
        categoryType: this.indexForm.categoryType,
        channelType: this.indexForm.channelType,
        startTime: this.startTime,
        endTime: this.endTime
      }).then(res => {
        var blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        var filename = res.headers.filename
        var downloadElement = document.createElement('a')
        var href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.style.display = 'none'
        downloadElement.href = href
        downloadElement.download = filename // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放掉blob对象
      }).catch(err => {
        console.log('err', err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
	// 样式请务必加scoped

</style>
